package com.example.juyixia;

import java.util.List;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.model.LatLng;
import com.example.juyixia.MyOrientationListener.OnOrientationListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Map_Activity extends Activity implements OnClickListener{
	private ImageView mIv_Back;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private Context context;//上下文
	private LocationClient mLocationClient;
	private MylocationListener mlocListener;
	private boolean isFirstIn = true;//用户是否是第一次请求定位
	private double mlatitude;//记录用户最新的纬度
	private double mlongitude;//记录用户最新的经度
	private LatLng meetLatLng;
	//下一步要在bin/res/AndroidManifest.xml中配置service
	
	private ImageView returnToMylocation;   //在界面上点击回到当前位置

	private BitmapDescriptor mIconPoint;//自定义指针图标
	private MyOrientationListener myOrientationListener;//自定义方向监听器
	private float mX;//记录当前的x坐标
	
	//自定义覆盖物相关声明
	private BitmapDescriptor mMarker;//商铺覆盖物
	private BitmapDescriptor meetMarker;//聚会位置覆盖物
	private RelativeLayout mMarkerLayout;//显示商店信息的布局
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	//	SDKInitializer.initialize(this);
        setContentView(R.layout.activity_baidumap); 
        this.context = this;
        Intent intent = getIntent();
        String str = intent.getStringExtra("message");
        if("我的位置".equals(str))
        	showMap1();
        if("活动".equals(str))
        	showMap2();
    }
	/**
	 * 从设置界面进入地图
	 */
	private void showMap1(){
		initViews();
        initLocation();
        //实例化回到我的位置
        returnToMylocation = (ImageView)findViewById(R.id.iv_myposition);
        //设置点击事件
        returnToMylocation.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub	
				turnToMyLocation();
			}
		});
	}
	/**
	 * 从活动界面进入地图
	 */
	private void showMap2(){
		initMarker();
		showMap1();
		addShopInfo(Map_shopInfo.infos);
		LatLng l = new LatLng(29.494300,106.580000);
		setMeetLatlng(l);
		turnToMeet(meetLatLng);
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(Marker marker) {
				// TODO Auto-generated method stub
				if(marker.getIcon()==mMarker){
					showMarkerLayout(marker);
					return true;
				}
				else
					return true;
			}
		});
        mBaiduMap.setOnMapClickListener(new OnMapClickListener() {
			
			@Override
			public boolean onMapPoiClick(MapPoi arg0) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void onMapClick(LatLng arg0) {
				// TODO Auto-generated method stub
				mMarkerLayout.setVisibility(View.GONE);//�Ѳ�����ʧ
				mBaiduMap.hideInfoWindow();
			}
		});
	}
	/**
	 * 初始化地图相关变量
	 */
	private void initViews() {
		// TODO Auto-generated method stub
		mIv_Back = (ImageView) findViewById(R.id.iv_back);
		mIv_Back.setOnClickListener(this);
		//获取地图的引用，初始化地图
		mMapView = (MapView) findViewById(R.id.baidumapView);
        mBaiduMap = mMapView.getMap();
        //将地图的比例设置为500米
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
	}
	/**
	 * 初始化覆盖物相关变量
	 */
	private void initMarker() {
		mMarker = 
			BitmapDescriptorFactory.fromResource(R.drawable.shop);
		meetMarker = 
			BitmapDescriptorFactory.fromResource(R.drawable.location);
		mMarkerLayout = (RelativeLayout) findViewById(R.id.showShopInfo);
	}
	/**
	 * 初始化定位相关变量
	 */
	private void initLocation() {
		mLocationClient = new LocationClient(this);
		mlocListener = new MylocationListener();
		//把listener注册到client
		mLocationClient.registerLocationListener(mlocListener);
		
		//进行相关设置
		LocationClientOption option = new LocationClientOption();
		//将经纬度设置成百度经纬度坐标
		option.setCoorType("bd09ll");
		//需要返回当前所在的位置
		option.setIsNeedAddress(true);
		//打开手机GPS
		option.setOpenGps(true);
		//设置向服务器的请求间隔为1秒
		option.setScanSpan(1000);
		//ִ执行以上设置
		mLocationClient.setLocOption(option);
		//初始化指针图标
		mIconPoint = 
				BitmapDescriptorFactory.fromResource(R.drawable.point);
		//初始化方向监听器
		myOrientationListener = new MyOrientationListener(context);
		myOrientationListener.setOnOrientationListener(new OnOrientationListener() {
			
			@Override
			public void OnOrientationChanged(float x) {
				// TODO Auto-generated method stub
				mX = x;
			}
		});	
	}
	//百度地图随着activity的生成而生成，消亡而消亡，实现地图的生命周期管理
	//以下为重写生命周期的几个方法
	@Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	mMapView.onResume();
    }
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	//将地图设置为允许定位
    	mBaiduMap.setMyLocationEnabled(true);
    	//判断是否开启了定位
    	if(!mLocationClient.isStarted())
    		mLocationClient.start();
    	//开启方向监听器
    	myOrientationListener.start();
    }
    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    	mMapView.onPause();
    }
    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	super.onStop();
    	//关闭定位
    	mBaiduMap.setMyLocationEnabled(false);
    	mLocationClient.stop();
    	//关闭方向监听器
    	myOrientationListener.stop();
    }
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	mMapView.onDestroy();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    /**
     * 菜单
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
    /**
     * 在地图上添加商铺信息
     * @param infos
     */
    private void addShopInfo(List<Map_shopInfo> infos) {
    	//先清除覆盖物
		mBaiduMap.clear();
		LatLng latLng = null;
		Marker marker = null;
		OverlayOptions options;
		for(Map_shopInfo info:infos){
			latLng = new LatLng(info.getLatitude(), info.getLongitude());
			options = new MarkerOptions()
			.position(latLng)
			.icon(mMarker)
			.zIndex(5);
			marker = (Marker) mBaiduMap.addOverlay(options);
			Bundle bundle = new Bundle();
			bundle.putSerializable("info", info);
			marker.setExtraInfo(bundle);
		}
		//
		MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
		mBaiduMap.setMapStatus(msu);
	}
    /**
     * 地图跳转到我的位置
     * */
	private void turnToMyLocation() {
		LatLng latLng = new LatLng(mlatitude,mlongitude);
		MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
		mBaiduMap.animateMapStatus(msu);
	}
	/**
	 * 地图跳转到聚会位置
	 */
	private void turnToMeet(LatLng meetLatlng){
		OverlayOptions option = new MarkerOptions()
		.position(meetLatlng)
		.icon(meetMarker)
		.zIndex(5);
		mBaiduMap.addOverlay(option);
		MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(meetLatlng);
		mBaiduMap.animateMapStatus(msu);
	}
	/**
	 * 显示商铺信息的布局
	 * @param marker
	 */
	private void showMarkerLayout(Marker marker) {
		Bundle extraInfo = marker.getExtraInfo();
		Map_shopInfo info =(Map_shopInfo) extraInfo
		.getSerializable("info");//从marker中取出商铺的信息
		//将布局与相关数据进行绑定
		ImageView iv = (ImageView) mMarkerLayout
				.findViewById(R.id.info_img);
		TextView shopName = (TextView)mMarkerLayout.findViewById(R.id.info_shopName);
		TextView shopDescription = (TextView)mMarkerLayout.findViewById(R.id.info_shopDescription);
		iv.setImageResource(info.getImage());
		shopName.setText(info.getName());
		shopDescription.setText(info.getDiscription());
		InfoWindow infoWindow;
		TextView tv = new TextView(context);
		tv.setBackgroundResource((R.drawable.tips));
		tv.setPadding(30, 20, 30, 50);
		tv.setText(info.getName());
		final LatLng latLng = marker.getPosition();
		infoWindow = new InfoWindow(tv,latLng,-60);
		mBaiduMap.showInfoWindow(infoWindow);
		mMarkerLayout.setVisibility(View.VISIBLE);//将隐藏的布局显示出来
	}
    /**
     * 自定义定位监听器
     * */
    private class MylocationListener implements BDLocationListener{
		@Override
		public void onReceiveLocation(BDLocation location) {
			// TODO Auto-generated method stub
			//真正定位自己的位置
//			MyLocationData data = new MyLocationData.Builder()
//			.direction(mX)
//			.accuracy(location.getRadius())
//			.latitude(location.getLatitude())
//			.longitude(location.getLongitude())
//			.build();
			//模拟定位自己的位置
			double lat = 29.494938;
			double longi = 106.579233;
			switch(Integer.parseInt(getIntent().getStringExtra("id"))){
			case 1:lat=29.494749;longi=106.576843;
			break;
			case 2:lat=29.495300;longi=106.581111;
			break;
			case 3:lat=29.493586;longi=106.581191;
			break;
			case 4:lat=29.496447;longi=106.578065;
			break;
			}
			MyLocationData data = new MyLocationData.Builder()
			.direction(mX)
			.accuracy(location.getRadius())
			.latitude(lat)
			.longitude(longi)
			.build();
			mBaiduMap.setMyLocationData(data);
			//将数据传给地图
			MyLocationConfiguration config 
			= new MyLocationConfiguration(
					LocationMode.NORMAL, true, mIconPoint);
			mBaiduMap.setMyLocationConfiguration(config);
			//更新最新的经纬度
			mlatitude = location.getLatitude();
			mlongitude = location.getLongitude();
			//判断用户是否是第一次请求定位
			if(isFirstIn){
				LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
				MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
				mBaiduMap.animateMapStatus(msu);
				isFirstIn = false;
				Toast.makeText(context, location.getAddrStr(), Toast.LENGTH_SHORT).show();
			}
		}
		//检测网络环境，是wifi还是流量
		@Override
		public void onConnectHotSpotMessage(String arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
	}
	public void setMeetLatlng(LatLng meetLatlng) {
		this.meetLatLng = meetLatlng;

	}
	public LatLng getMyLatlng(){
		return new LatLng(mlatitude, mlongitude);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;

		default:
			break;
		}
	}
}
